package com.znsd.zl.dict.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @ClassName JsonUtils
 * @Description 自定义响应结构, 转换类
 * @Author zhubin
 * @Date 2020/8/19 11:22
 * @Version v1.0
 */
@Slf4j
public class JsonUtils {
	private static final ObjectMapper MAPPER = new ObjectMapper();

	/**
	 *  将对象转换成json字符串
	 * @param data
	 * @return
	 */
	public static String objectToJson(Object data) {
		String json = null;
		try {
			json = MAPPER.writeValueAsString(data);
			log.info("对象转换字符======》" + json);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return json;
	}

	/**
	 *  json字符串转换成对象
	 * @param jsonData json字符串
	 * @param beanType 转换类型
	 * @param <T>   指定泛型，方法参数beanType什么类型就是什么类型
	 * @return
	 */
	public static <T>T jsonToObject(String jsonData, Class<T> beanType) {
		T t = null;
		try {
			t = MAPPER.readValue(jsonData,beanType);
			log.info("字符转换对象======》" + t);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return t;
	}

}
